package com.sgb.member.view_model;

import com.sgb.member.MemberConfig;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ListMResponse;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberCompanyTeamBean;
import com.sgb.member.entity.MemberGoodsListEntity;
import com.sgb.member.entity.MemberLeaseBean;
import com.sgb.member.entity.MemberQuotePriceBean;
import com.sgb.member.ui.fragment.CompanyWebBusinessFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.PointUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * Time:2021/4/30
 * AUTHOR:F_Q
 * Description:
 */
public class CompanyWebBusinessModel extends BaseViewModel {

    CompanyWebBusinessFragment fragment;
    MemberRepertory repertory;
    int current;

    private final String mCompanyNo;

    public CompanyWebBusinessModel(CompanyWebBusinessFragment fragment, MemberRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
        mCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
    }

    public void showOrHideDialog(boolean aBoolean) {
        if (aBoolean) {
            if (!DialogHelper.isShowing()) {
                DialogHelper.showProgressDialog(fragment.getActivity(), "数据获取中...");
            }
        } else {
            DialogHelper.dismissProgressDialog();
        }
    }

    public void getBusinessData(String flag,int curPos, boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        if(flag.equals("1")){//查价
            switch (curPos) {
                case 0: // "经营商品"
                    getProducts2(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
                case 1: // "租赁经营"
                    getLeases2(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
                case 2: // "工程工队"
                    getTeams2(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
            }
        }else {//调价
            switch (curPos) {
                case 0: // "经营商品"
                    getProducts(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
                case 1: // "租赁经营"
                    getLeases(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
                case 2: // "工程工队"
                    getTeams(isLoadMore, quotedCompanyNo,mNo1,mNo2,mNo3);
                    break;
            }
        }
    }

    private void getProducts(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("item_cid1", mNo1);
        map.put("item_cid2", mNo2);
        map.put("item_cid", mNo3);
        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().getCompanyWebGoodsList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberGoodsListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberGoodsListEntity>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberGoodsListEntity>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    private void getProducts2(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("item_cid1", mNo1);
        map.put("item_cid2", mNo2);
        map.put("item_cid", mNo3);
        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().queryPriceCommodityList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberGoodsListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberGoodsListEntity>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberGoodsListEntity>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    private void getLeases(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("type", mNo1);
        map.put("firstCategoryNo",mNo2 );
        map.put("secondCategoryNo", mNo3);
        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().getCompanyWebRentList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberLeaseBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberLeaseBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberLeaseBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    private void getLeases2(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("type", mNo1);
        map.put("firstCategoryNo",mNo2 );
        map.put("secondCategoryNo", mNo3);
        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().queryPriceRentList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberLeaseBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberLeaseBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberLeaseBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }


    private void getTeams(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("catgoryNo", mNo1);

        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().getCompanyWebTeamList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    private void getTeams2(boolean isLoadMore, MemberBean quotedCompanyNo,String mNo1,String mNo2, String mNo3) {
        showOrHideDialog(true);
        int curPager = isLoadMore ? current + 1 : 1;
        int maxPageSize = 10;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", curPager);
        map.put("limit", maxPageSize);
        map.put("categoryType", mNo1);

        // 1供方会员 2需方会员
        if (quotedCompanyNo.getMemberUpdateLeverType().equals("1")) {
            map.put("companyNo", quotedCompanyNo.getCompanyNo());// 我的no
            map.put("quotedCompanyNo", mCompanyNo);//报价公司no
        } else {
            map.put("companyNo", mCompanyNo);// 我的no
            map.put("quotedCompanyNo", quotedCompanyNo.getCompanyNo());//报价公司no
        }
        repertory.getApi().queryPriceTeamPriceList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberCompanyTeamBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    public void getH5Url(int pos, String id) {
        String name = "";
        if (pos == 1) {
            name = "mechanicsDetail";//机械
        } else if (pos == 2) {
            name = "equipmentDetails";//设备
        } else if (pos == 3) {
            name = "vehicleDetails";//车辆
        } else if (pos == 4) {
            name = "propertyDetails";//房产
        } else if (pos == 5) {
            name = "landDetails";//土地
        } else if (pos == 6) {
            name = "factoryDetails";//工厂
        } else if (pos == 7) {
            name = "farmDetail";//农机
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.getApi().getUrlSetting(name).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?id=" + id;
                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url);
            }
        });
    }

    public void getTeamH5Url(String id) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.getApi().getUrlSetting("teamWorkDetail").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?no=" + id + "&type=0";
                MLog.d("api", "H5跳转链接  " + url);
                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url);
            }
        });
    }


    public void updateQuotePrice(int curPage, String no, Object mObject, String o, int updateIndex) {
        showOrHideDialog(true);
        MemberQuotePriceBean priceBean = new MemberQuotePriceBean();
        priceBean.companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        //   priceBean.quotedType = ""; //1 商品报价 2 租赁报价 3 团队报价
        switch (curPage) {
            case 0:
                MemberGoodsListEntity entity = (MemberGoodsListEntity) mObject;
                priceBean.quotedType = "1";
                priceBean.quotedCompanyNo = no;
                MemberQuotePriceBean.GoodQuoteBean goodQuoteBean = new MemberQuotePriceBean.GoodQuoteBean();
                goodQuoteBean.businessNo = entity.getSkuid();
                goodQuoteBean.companyNo = priceBean.companyNo;
                goodQuoteBean.quotedCompanyNo = priceBean.quotedCompanyNo;
                goodQuoteBean.price = PointUtils.price(Double.parseDouble(o));
                goodQuoteBean.originalPrice = entity.getPrice();
                goodQuoteBean.differencePrice = Double.parseDouble(o) - entity.getPrice();
                goodQuoteBean.lastPrice = entity.getQuetePrice();
                goodQuoteBean.brandId = entity.getBrandId();
                goodQuoteBean.firstCategoryNo = entity.getCid1();
                goodQuoteBean.secondCategoryNo = entity.getCid2();
                goodQuoteBean.thirdCategoryNo = entity.getCid();
                goodQuoteBean.itemId = entity.getId();
                goodQuoteBean.title = entity.getCartTitle();
                goodQuoteBean.unit = entity.getUnit();
                List<MemberQuotePriceBean.GoodQuoteBean> goodQuoteBeans = new ArrayList<>();
                goodQuoteBeans.add(goodQuoteBean);
                priceBean.goodsQuotePriceList = goodQuoteBeans;
                break;
            case 1:
                MemberLeaseBean leaseBean = (MemberLeaseBean) mObject;
                priceBean.quotedType = "2";
                priceBean.quotedCompanyNo = no;
                MemberQuotePriceBean.RentQuoteBean rentQuoteBean = new MemberQuotePriceBean.RentQuoteBean();
                rentQuoteBean.companyNo = priceBean.companyNo;
                rentQuoteBean.quotedCompanyNo = priceBean.quotedCompanyNo;
                rentQuoteBean.price = PointUtils.price(Double.parseDouble(o));
                rentQuoteBean.originalPrice = Double.parseDouble(leaseBean.getPrice());
                rentQuoteBean.differencePrice = Double.parseDouble(o) - Double.parseDouble(leaseBean.getPrice());
                rentQuoteBean.firstCategoryNo = leaseBean.getFirst_category();
                rentQuoteBean.secondCategoryNo = leaseBean.getSecond_category();
                rentQuoteBean.businessNo = leaseBean.getNo();
                rentQuoteBean.businessType = leaseBean.getType();
                rentQuoteBean.categoryName = leaseBean.getCategory();
                rentQuoteBean.title = leaseBean.getTitle();
                rentQuoteBean.unit = leaseBean.getPriceUnit();
                List<MemberQuotePriceBean.RentQuoteBean> rentQuoteBeans = new ArrayList<>();
                rentQuoteBeans.add(rentQuoteBean);
                priceBean.rentQuotePriceList = rentQuoteBeans;
                break;
            case 2:
                MemberCompanyTeamBean findBean = (MemberCompanyTeamBean) mObject;
                priceBean.quotedType = "3";
                priceBean.quotedCompanyNo = no;
                MemberQuotePriceBean.TeamQuoteBean teamQuoteBean = new MemberQuotePriceBean.TeamQuoteBean();
                teamQuoteBean.companyNo = priceBean.companyNo;
                teamQuoteBean.quotedCompanyNo = priceBean.quotedCompanyNo;
                teamQuoteBean.price = PointUtils.price(Double.parseDouble(o));
                teamQuoteBean.originalPrice = Double.parseDouble(findBean.getPrice());
                teamQuoteBean.differencePrice = Double.parseDouble(o)- Double.parseDouble(findBean.getPrice());
                teamQuoteBean.businessNo = findBean.getCompany_no();
                teamQuoteBean.teamName = findBean.getTeam_name();
                teamQuoteBean.typeWork = findBean.getType_work();
                teamQuoteBean.unit = findBean.getUnit();
                List<MemberQuotePriceBean.TeamQuoteBean> teamQuoteBeans = new ArrayList<>();
                teamQuoteBeans.add(teamQuoteBean);
                priceBean.teamQuotePriceList = teamQuoteBeans;
                break;
        }
        repertory.getApi().quotePriceByType(priceBean).enqueue(new ICallBack<BaseEntity<BaseEntity<String>>>() {
            @Override
            public void onSuccess(BaseEntity<BaseEntity<String>> data) {
                fragment.updateQuotePriceCallback(updateIndex, o);
            }
        });
    }

    private List<CommonPopEntity> list;
    //  商品类型（industryId:一级类目id，areaCode:省份id)
    public void getAllCategory() {
        showOrHideDialog(true);
        repertory.getApi().getCatList(repertory.getAreaCode()).enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    list = new ArrayList<>();
                    list.add(new CommonPopEntity("","全部"));
                    list.addAll(data.getData());
                    fragment.setTablayout1(list);
                }
            }
        });
    }

    // 会员租赁
    public void getAllLeaseType() {
        // 1机械， 2 设备，3车辆，4 房产，5土地，6工厂，7农机
        // "工程机械", "工程设备", "车辆租赁", "房产租赁", "土地租赁", "工厂租赁", "农机租赁"
        showOrHideDialog(true);
        repertory.getApi().getRentCategory().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    list = new ArrayList<>();
                    list.add(new CommonPopEntity("","全部"));
                    list.addAll(data.getData());
                    fragment.setTablayout1(list);
                }
            }
        });
    }

    // 工队
    public void getAllTeamType() {
        showOrHideDialog(true);
        repertory.getApi().getCategoryTrees(repertory.getAreaCode(), "0").enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    list = new ArrayList<>();
                    list.add(new CommonPopEntity("","全部"));
                    list.addAll(data.getData());
                    fragment.setTablayout1(list);
                }
            }
        });
    }

    // 二级
    private List<CommonPopEntity> list2 =new ArrayList<>();
    public void getCategoryChoose(int position) {
        list2.clear();
        if(position!=0){
            if(list.get(position).getChildren().size()>0){
                list2.add(new CommonPopEntity("","全部"));
                list2.addAll(list.get(position).getChildren());
            }
        }
        fragment.setTablayout2(list2);
    }

    // 三级
    private List<CommonPopEntity> list3 =new ArrayList<>();
    public void getCateArguments(int position) {
        list3.clear();
        if(position!=0){
            if(list2.get(position).getChildren().size()>0){
                list3.add(new CommonPopEntity("","全部"));
                list3.addAll(list2.get(position).getChildren());
            }
        }
        fragment.setTablayout3(list3);
    }
}
